﻿using AutoMapper;
using MediatR;
using T.S.BaseData.Api.AppClinet.Commend.Imgs;
using T.S.BaseData.Domain.Entity;
using T.S.BaseData.ErrorCode;
using T.S.BaseData.Infrastructure.Base;

namespace T.S.BaseData.Api.AppClinet.CommendHand.Imgs
{
    public class ImgCreateCommandHandle : IRequestHandler<ImgCreateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Img> imRepo;
        private readonly IMapper mapper;
        private readonly ILogger<ImgCreateCommandHandle> logger;
        private readonly IBaseRepository<BasicInfo> basicRepo;


        public ImgCreateCommandHandle(IBaseRepository<Img> imRepo,
            IMapper mapper,
            ILogger<ImgCreateCommandHandle> logger,
            IBaseRepository<BasicInfo> basicRepo)
        {
            this.imRepo = imRepo;
            this.mapper = mapper;
            this.logger = logger;
            this.basicRepo = basicRepo;
        }

        public Task<ApiResult<int>> Handle(ImgCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var basic = basicRepo.GetAll().Where(x => x.GoodsId == request.GoodsId).FirstOrDefault();

            var model = mapper.Map<Img>(request);
            model.BasicBatch = basic.GoodsBatch;

            var r = imRepo.Crate(model);
            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Data = r;
                result.Meg = "添加图片信息成功";

                logger.LogInformation("添加图片信息成功");

            }
            else
            {
                result.Code = ApiEnums.Error;
                result.Data = r;
                result.Meg = "添加图片信息失败";

                logger.LogInformation("添加图片信息失败");

            }

            return Task.FromResult(result);

        }
    }
}
